package com.campus.app.service.impl;

import com.campus.app.service.FunctionServer;
import com.campus.commons.entity.*;
import com.campus.commons.entity.Class;
import com.campus.commons.utils.Tool;
import com.campus.commons.utils.excel.EasyPoiRead;
import io.swagger.models.auth.In;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Service
public class FunctionServerImpl implements FunctionServer {
    public static Map<String, Integer> classes = new HashMap<>();
    public static Map<String, Integer> teachers = new HashMap<>();
    public static Map<String, Integer> classRooms = new HashMap<>();
    public static Map<String, Integer> students = new HashMap<>();

    /**
     * 初始化方法； 每次读取表格都需要调用；
     */
    public static void init() {
        if (classes.size() != Class.classes.size()) {
            classes.clear();
            Class.classes.keySet().stream().forEach(v -> classes.put(Class.classes.get(v).getClassname(), v));
        }
        if (classRooms.size() != ClassRoom.classrooms.size()) {
            classRooms.clear();
            ClassRoom.classrooms.keySet().stream().forEach(v -> classRooms.put(ClassRoom.classrooms.get(v), v));
        }
        if (teachers.size() != Teacher.teachers.size()) {
            teachers.clear();
            Teacher.teachers.keySet().stream().forEach(v -> teachers.put(Teacher.teachers.get(v).getTeachername(), v));
        }
        if (students.size() != Student.students.size()) {
            students.clear();
            Student.students.keySet().stream().forEach(v-> students.put(Student.students.get(v).getStuname(),v));
        }


    }

    @Override
    public List<EveningSubject> upLoadEveningSubject(InputStream upFile, String fileName) throws IOException {
        init();
        Workbook workbook = EasyPoiRead.getWorkbook(upFile, fileName);
        List<EveningSubject> list = new ArrayList<>();
        Sheet sheetAt = workbook.getSheetAt(0);
        //获取日期;
        CellRangeAddress week1 = EasyPoiRead.getMergedRegions(sheetAt, "星期一.*").get(0);
        String weekStr = EasyPoiRead.getValue(sheetAt, week1.getFirstRow(), week1.getFirstColumn()).toString().substring(3);
        // 周一; 时间
        Date date = Tool.getDate(Calendar.getInstance().get(Calendar.YEAR) + "年" + weekStr, "yyyy年 MM 月 dd 日");
        // 获取读取的行;
        List<CellRangeAddress> mergedRegions = EasyPoiRead.getMergedRegions(sheetAt, "周.课表");
        int size = mergedRegions.size();
        for (int i = 0; i < size; i++) {
            Integer start = mergedRegions.get(i).getFirstRow() + 1;
            Integer end = i < (size - 1) ? mergedRegions.get(i + 1).getFirstRow() - 1 : sheetAt.getLastRowNum(); //最后一行;
            //结果集； param 0 班级  3 教室 1 老师 都需要处理；
            List<Map<String, Object>> values = EasyPoiRead.getValues(sheetAt, start, end, 2, 4, 5, 6);
            values.stream().forEach(v -> {
                Integer classI = classes.get(v.get("param0").toString());
                Integer classId = classI==null?-1:classI;
                Integer teacherI = teachers.get(v.get("param1").toString());
                Integer teacherId = teacherI==null?-1:teacherI;
                Integer classroomI = classRooms.get(v.get("param3").toString());
                Integer classroomId = classroomI==null?-1:classroomI;
                //添加
                list.add(new EveningSubject(date, classId, teacherId, v.get("param2").toString(), classroomId));
                Tool.diffDate(date, 1); //获取第二天;
            });
        }
        return list;
    }

    @Override
    public List<Counsellor> upLoadCounsellor(InputStream upFile, String fileName) throws IOException {
        init();
        Workbook workbook = EasyPoiRead.getWorkbook(upFile, fileName);
        Sheet sheetAt = workbook.getSheetAt(0);
//       晚自习；
        List<Counsellor> list = new ArrayList<>();
        //获取日期;
        Date date = (Date) EasyPoiRead.getValue(sheetAt, 4, 0, true);
        // 获取读取的行;
        List<CellRangeAddress> mergedRegions = EasyPoiRead.getMergedRegions(sheetAt, "周.");
        int size = mergedRegions.size();
        for (int i = 0; i < size; i++) {
            Integer start = mergedRegions.get(i).getFirstRow() + 1;
            Integer end = i < (size - 1) ? mergedRegions.get(i + 1).getFirstRow() - 1 : sheetAt.getLastRowNum(); //最后一行;
            List<Map<String, Object>> values = EasyPoiRead.getValues(sheetAt, start, end, 2, 4, 6);
            values.stream().forEach(v -> {
                Integer integer1 = classRooms.get(v.get("param0").toString());
                Integer classroomId = integer1==null?-1:integer1;
                Integer integer2 = classes.get(v.get("param1").toString());
                Integer classId = integer2==null?-1:integer2;
                Integer integer = students.get(v.get("param2").toString());
                boolean param2 = v.get("param2").toString().equals("");
                //如果为空 -1，没匹配到0 ；
                Integer studentId = param2?0:integer==null?-1:integer;
//                //添加
                list.add(new Counsellor(date, classroomId, studentId, classId));
                System.out.println();
                Tool.diffDate(date, 1); //获取第二天;
            });
        }
        workbook.close();
        return list;
    }

    //<editor-fold desc="课表读取">
    @Override
    public List<Course> upLoadCourse(InputStream upFile, String fileName) throws IOException {
        init();
        Workbook workbook = EasyPoiRead.getWorkbook(upFile, fileName);
        List<Course> list = new ArrayList<>(); //返回的数据;
        Sheet hs = workbook.getSheetAt(1); //获取第一页
        Row row1 = hs.getRow(3);
        Cell cell1 = row1.getCell(0);
        Date date = cell1.getDateCellValue(); //周一的时间
        int start = 3; //起始行
        for (int i = 0; i < (hs.getLastRowNum() / 25); i++) {
            row(hs, start, (start + 21), date, list);
            date = Tool.diffDate(date, 1);
            start += 23;
        }
        return list;
    }

    private void row(Sheet hs, int start, int end, Date date, List<Course> list) {
//        外层循环
        for (int i = start; i < end; i++) {
            Row row = hs.getRow(i); //获取行
            try {
                coll(2, row, 1, date, 3, list);
                coll(7, row, 2, date, 8, list);
            } catch (NullPointerException e) {

            }
        }
    }
    //循环每一列，执行添加，或者保存起来返回List 然后校验好了再添加数据库

    /**
     * 筛选列数据， 然后保存到List||数据库
     *
     * @param start    列开始位置
     * @param row      行引用
     * @param forenoon 上午还是下午
     * @param date     日期
     * @param coll     班级列，需要特殊格式处理
     */
    private void coll(int start, Row row, int forenoon, Date date, int coll, List<Course> courses) {
        List<Object> list = new ArrayList<>();
        for (int j = start; j < (start + 4); j++) {
            Cell cell = row.getCell(j);
            String value = cell.getStringCellValue();
            //班级
            if (j == coll) {
                if (cell.getStringCellValue() == null || value.length() == 0) {
                    return;
                }
                if (value.indexOf("T") != -1) {
                    int starti = value.lastIndexOf("T");
//                        int endi = cell.getStringCellValue().indexOf("（") != -1 ? value.length() - 1 : value.length();
                    int end = starti + 5;
                    value = value.substring(starti, end); //班级
                    System.out.print(value + "\t");
                }
            } //格式处理代码
            list.add(value);
        }
        // 这里执行发送  或者  保存 代码
        String classroom = (String) list.get(0);
        String grade = (String) list.get(1);
        String teacher = (String) list.get(2);
        String subjectContent = (String) list.get(3);
        //将名字转换成Id;
        int classId = classes.get(grade) == null ? -1 : classes.get(grade);
        int teacherId = teachers.get(teacher) == null ? -1 : teachers.get(teacher);
        int classroomId = classRooms.get(classroom) == null ? -1 : classRooms.get(classroom);
        Course course = new Course(classId, classroomId, teacherId, subjectContent, forenoon, date);
        courses.add(course);
    }
    //</editor-fold>


}
